package com.leetcode;

import java.util.HashMap;
import java.util.Map;

/**
 * 13. 罗马数字转整数
 *
 * @author fy
 * @date 2023/2/2 19:43
 */
public class Solution13 {
    Map<String, Integer> chNums = new HashMap<String, Integer>(7) {{
        put("I", 1);
        put("IV", 4);
        put("V", 5);
        put("IX", 9);
        put("X", 10);
        put("XL", 40);
        put("L", 50);
        put("XC", 90);
        put("C", 100);
        put("CD", 400);
        put("D", 500);
        put("CM", 900);
        put("M", 1000);
    }};

    public int romanToInt(String s) {
        int sum = 0;

        for(int i = 0; i < s.length();) {
            char ch = s.charAt(i);
            int chIndex = chNums.get(String.valueOf(ch));
            int nextIndex = 0;
            if (i + 1 < s.length()) {
                char next = s.charAt(i + 1);
                nextIndex = chNums.get(String.valueOf(next));
            }
            if (nextIndex > chIndex) {
                sum += chNums.get(String.valueOf(ch) + s.charAt(i + 1));
                i += 2;
            } else {
                sum += chNums.get(String.valueOf(ch));
                i++;
            }
        }

        return sum;
    }

}
